package com.wzh.prac.lucene01;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;


import java.nio.file.Paths;

/**
 * Created with IntelliJ IDEA.
 * User: wzh
 * Date: 2016/2/24
 * Time: 13:58
 */
public class Searcher {

    public static void search(String indexDir,String q) throws Exception{
        //打开索引目录
        Directory dir= FSDirectory.open(Paths.get(indexDir));
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher indexSearcher = new IndexSearcher(reader);
        Analyzer analyzer = new StandardAnalyzer();
        QueryParser parser =  new QueryParser("content",analyzer);
        Query query = parser.parse(q);
        long start=System.currentTimeMillis();
        TopDocs hits=indexSearcher.search(query, 10);
        long end=System.currentTimeMillis();
        System.out.println("查找的时间为:"+(end-start)+" 毫秒");

        for(ScoreDoc scoreDoc : hits.scoreDocs){
            Document doc  =indexSearcher.doc(scoreDoc.doc);
            System.out.println(doc.get("content"));
        }
        reader.close();
    }

    public static void main(String[] args) {
        String indexDir="F:\\index";
        String q="Zygmunt Saloni";
        try {
            search(indexDir,q);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
